package com.mo.lib.ui.dialog

import android.annotation.TargetApi
import android.app.Activity
import android.os.Build
import android.view.TextureView
import android.view.View
import com.dylanc.longan.topActivity
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.mo.lib.R
import com.mo.lib.ui.action.HandlerAction
import com.mo.lib.utils.CameraHelper
import com.mo.lib.utils.KLog
import com.mo.lib.utils.showToast

/**
 * @ author：mo
 * @ data：2020/9/23:16:53
 * @ 功能：拍照弹窗
 */
class CarmeraDialog(  private val onTakePic: CameraHelper.OnTakePic) : BaseDialog( R.layout.dialog_camera), HandlerAction {
    private var mTextureView: TextureView? = null
    private var mHelper: CameraHelper? = null

    init {
        mHelper = CameraHelper(topActivity, mTextureView) { isSave, targetFile, path, bitmap ->
            onTakePic.getTakeResult(isSave, targetFile, path, bitmap)
            dismisss()
        }
    }

    override fun show() {
        XXPermissions.with(topActivity).permission(Permission.CAMERA).request { permissions, all ->
            run {
                if (all) {
                    super.show()
                } else {
                    showToast("缺少相机权限！")
                }
            }
        }

    }
    override fun doWhat() {
        setDialogScale(1.0)
        setDismissType(DismissType.BACK)
        mTextureView = dialog.findViewById(R.id.textureView)
        val iv_dialog_camera_back = dialog.findViewById<View>(R.id.iv_dialog_camera_back)
        iv_dialog_camera_back.setOnClickListener { dialog.dismiss() }
        val iv_dialog_camera_take = dialog.findViewById<View>(R.id.iv_dialog_camera_take)
        iv_dialog_camera_take.setOnClickListener { takePicture() }
        postDelayed({
            iv_dialog_camera_back.visibility = View.VISIBLE
            iv_dialog_camera_take.visibility = View.VISIBLE
        }, 1000)
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    fun takePicture() {
        if (mHelper != null) {
            mHelper!!.takePic()
        } else {
            KLog.i("mHelper未创建实例！")
        }
    }

}